﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using log4net;
using tinfosvr.Models;
using Fleck;
using System.Timers;

namespace tinfosvr
{
    class TrainTimesServer
    {
        private List<WebSocketClient> mAllSockets = new List<WebSocketClient>();
        private WebSocketServer mServer = null;

        public void Init()
        {
            FleckLog.Level = LogLevel.Debug;
            mServer = new WebSocketServer("ws://0.0.0.0:8080");
            mServer.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    OnWebSocketOpen(socket);
                };
                socket.OnClose = () =>
                {
                    OnWebSocketClose(socket);
                };
                socket.OnMessage = message =>
                {
                    OnWebSocketRecvMsg(socket, message);
                };

                socket.OnBinary = bytes =>
                {
                    OnWebSocketRecvBytes(socket, bytes);
                };
            });
        }

        public  void dispose()
        {
            if(mServer != null)
            {
                mServer.Dispose();
                mServer = null;
            }
        }

        private void OnWebSocketOpen(IWebSocketConnection socket)
        {
            mAllSockets.Add(new WebSocketClient(socket));
        }

        private void OnWebSocketClose(IWebSocketConnection socket)
        {
            var clients = mAllSockets.Where(x => x == socket).ToList();
            foreach (var client in clients)
            {
                mAllSockets.Remove(client);
            }
        }

        private void OnWebSocketRecvMsg(IWebSocketConnection socket, string message)
        {            //socket.Send("Echo: " + message);
            var clients = mAllSockets.Where(x => x == socket).ToList(); 
            foreach(var client in clients)
            {
                client.OnRecvMsg(message);
            }
        }

        private void OnWebSocketRecvBytes(IWebSocketConnection socket, byte [] bytes)
        {

        }
    }

    class WebSocketClient
    {
        private IWebSocketConnection mSocket = null;
        private Timer mTimer = null;
        private List<qy_platform> mPlatforms = null;
        public WebSocketClient(IWebSocketConnection conn)
        {
            mSocket = conn;
        }

        private void StartPushTrainTimes()
        {
            mTimer = new Timer();
            mTimer.Interval = 1000;
            mTimer.Elapsed += MTimer_Elapsed;
            mTimer.Start();
        }

        private void MTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            mTimer.Stop();
            try
            {
                SendTrainTimesInfo();
            }
            catch(Exception ex)
            {

            }
            finally
            {
                mTimer.Start();
            }

        }

        private void StopPushTrainTimes()
        {
            if(mTimer != null)
            {
                mTimer.Stop();
            }
        }

        private void SendTrainTimesInfo()
        {
            trainTimes obj = new trainTimes();
            obj.status = 1;
            obj.msg = "success";

            foreach (qy_platform sinfo in mPlatforms)
            {
                data d = new data();
                TrainTimesUpdater.GetInstance().UpdateTrainTimesInfo(sinfo);
                d.station_id = sinfo.station_id;
                d.direction = sinfo.direction;
                d.current_train = sinfo.current_train;
                d.next_train = sinfo.next_train;
                obj.data.Add(d);
            }


            string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            mSocket.Send(json);
        }

        public void OnRecvMsg(string message)
        {
            StopPushTrainTimes();

            string[] array = message.Split("|");
            if (array.Last().ToLower().Equals("yunying"))
            {
                string[] sids = array.First().Split(',');
                mPlatforms = new List<qy_platform>();
                foreach (string sid in sids)
                {
                    if (sid.Trim().Length > 0)
                    {
                        mPlatforms.AddRange(TrainTimesUpdater.GetInstance().GetPlatform(131, int.Parse(sid)));
                    }
                }
                SendTrainTimesInfo();
                StartPushTrainTimes();
            }
            else if (array.Last().ToLower().Equals("tixing'"))
            {

            }
            else if (array.Last().ToLower().Equals("notixing"))
            {

            }
        }

        public void dispose()
        {
            StopPushTrainTimes();
        }
    }

    class data
    {
        public int station_id = 0;
        public string direction = "";
        public int current_train = 0;
        public int next_train = 0;
    }

    class trainTimes
    {
        public int status = 0;
        public string msg = "";
        public List<data> data = new List<data>();
    }
}
